package com.zyjc.city.exception;

import com.zyjc.city.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ckj
 * @date 2024年03月31日 11:12
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public Result handleDemoModeException(BusinessException e) {
        return Result.fail(e.getDescription());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result paramHandler(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        String field = result.getFieldErrors().get(0).getField();
        String message = result.getFieldErrors().get(0).getDefaultMessage();
        map.put(field,message);
        return Result.fail("参数校验异常",map);
    }

    @ExceptionHandler(Exception.class)
    public Result defaultHandler(Exception e) {
        log.error("系统错误",e);
        return Result.fail(e.getMessage());
    }


}
